from sqlalchemy import insert, update
from sqlalchemy.exc import IntegrityError
from sqlalchemy.ext.asyncio import AsyncSession

from src.infrastructure.date_helpers import get_date_time
from src.infrastructure.db.models import Statistics


async def update_stats(
    session: AsyncSession,
    mobile_proxies_bought: int = 0,
    server_proxies_bought: int = 0,
    payments_payed: int = 0,
    messages_sent: int = 0,
    subscriptions: int = 0,
    vpns: int = 0,
) -> None:
    cur_date = get_date_time().date()
    try:
        await session.execute(
            insert(Statistics).values(
                day=cur_date,
                mobile_proxies_bought=mobile_proxies_bought,
                server_proxies_bought=server_proxies_bought,
                payments_payed=payments_payed,
                messages_sent=messages_sent,
                subscriptions=subscriptions,
                vpns=vpns,
            )
        )
    except IntegrityError:
        await session.execute(
            update(Statistics)
            .where(Statistics.day == cur_date)
            .values(
                mobile_proxies_bought=Statistics.mobile_proxies_bought + mobile_proxies_bought,
                server_proxies_bought=Statistics.server_proxies_bought + server_proxies_bought,
                payments_payed=Statistics.payments_payed + payments_payed,
                messages_sent=Statistics.messages_sent + messages_sent,
                subscriptions=Statistics.subscriptions + subscriptions,
                vpns=Statistics.vpns + vpns,
            )
        )
    await session.commit()
